const mysql = require('mysql2/promise');

// 创建数据库连接池
const pool = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: '123456',
  database: 'frontend_assistant',  // 使用统一的数据库
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

// 数据库连接函数
const connectDB = async () => {
  try {
    // 首先创建一个没有指定数据库的连接
    const tempPool = mysql.createPool({
      host: 'localhost',
      user: 'root',
      password: '123456'
    });

    // 创建数据库
    await tempPool.query('CREATE DATABASE IF NOT EXISTS frontend_assistant');
    await tempPool.end();

    // 使用新创建的数据库
    const connection = await pool.getConnection();
    console.log('数据库连接成功');
    
    // 创建 plans 表
    await connection.query(`
      CREATE TABLE IF NOT EXISTS plans (
        id INT PRIMARY KEY AUTO_INCREMENT,
        name VARCHAR(255) NOT NULL,
        date DATE NOT NULL,
        time_type ENUM('morning', 'noon', 'afternoon', 'evening') NOT NULL,
        time TIME NOT NULL,
        notified BOOLEAN DEFAULT FALSE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
      )
    `);

    // 创建面试题表
    await connection.query(`
      CREATE TABLE IF NOT EXISTS interview_questions (
        id INT PRIMARY KEY AUTO_INCREMENT,
        question TEXT NOT NULL,
        answer TEXT,
        category VARCHAR(50),
        difficulty ENUM('easy', 'medium', 'hard'),
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
      )
    `);
    
    connection.release();
  } catch (error) {
    console.error('数据库连接失败:', error);
    process.exit(1);
  }
};

module.exports = { pool, connectDB }; 